from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel, Field
from db_utils import Database, VectorStore, DocumentManager

# 数据库依赖
def get_db():
    db = Database()
    session = db.connect()
    try:
        yield db
    finally:
        db.disconnect(session)


# 向量存储依赖
def get_vector_store(db: Database = Depends(get_db)):
    return VectorStore(db)


# 文档管理器依赖
def get_document_manager(db: Database = Depends(get_db)):
    return DocumentManager(db)


# Pydantic模型定义
class CategoryCreate(BaseModel):
    name: str = Field(..., min_length=1, max_length=100, description="分类名称")
    description: str | None = Field(None, description="分类描述")


class CategoryResponse(CategoryCreate):
    id: int

    class Config:
        from_attributes = True


class DocumentCreate(BaseModel):
    content: str = Field(..., min_length=1, description="文档内容")
    category_ids: list[int] | None = Field([], description="分类ID列表")
    title: str | None = Field(None, max_length=255, description="文档标题")


class DocumentResponse(DocumentCreate):
    id: int
    created_at: str
    updated_at: str

    class Config:
        from_attributes = True


class SearchRequest(BaseModel):
    query: str = Field(..., min_length=1, description="搜索查询文本")
    top_k: int = Field(5, ge=1, le=50, description="返回结果数量")
    category_id: int | None = Field(None, description="分类ID")


class SearchResult(BaseModel):
    id: int
    content: str
    title: str | None
    similarity: float
    category_ids: list[int] | None = []